//
//  SearchViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/12.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit

class SearchViewController: UIViewController {

    var backButton: UIButton?
    
    let db = RecentSearchDB.getShareInstance()
    
    let searchIcon: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "search")
        return imageView
    }()
    
    let textfield: UITextField = {
        let textfield = UITextField()
        textfield.placeholder = LanguageHelper.getString(key: "TYPE_RESTAURANT_NAME")
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.black
        textfield.returnKeyType = .done
        return textfield
    }()
    
    let saperator: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.lightGray
        return view
    }()
    
    let recentTitleView: FilterTitleView = {
        let titleView = FilterTitleView()
        titleView.label.text = LanguageHelper.getString(key: "RECENT_SEARCH")
        return titleView
    }()
    
    var recentSearch: [RecentSearch] = []
    
    var labels: [UILabel] = []
    
    var completion: ((String) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        backButton = UIButton()
        backButton?.frame = CGRect(x: 12, y: 32, width: 18, height: 18)
        backButton?.setImage(UIImage(named: "back_black"), for: .normal)
        backButton?.addTarget(self, action: #selector(backForButton(_:)), for: .touchUpInside)
        self.view.addSubview(backButton!)
        
        textfield.delegate = self
        searchIcon.frame = CGRect(x: 90, y: 35, width: 15, height: 15)
        textfield.frame = CGRect(x: 110, y: 34, width: 160, height: 17)
        self.view.addSubview(searchIcon)
        self.view.addSubview(textfield)
        
        saperator.frame = CGRect(x: 0, y: 65, width: self.view.bounds.width, height: 0.5)
        self.view.addSubview(saperator)
        
//        let textMaxSize = CGSize(width: self.view.bounds.width, height: 25)
//        let titleWidth = TextSize.textSize(text: hot.text!, font: AppFont(size: 17), maxSize: textMaxSize).width
//        hot.frame = CGRect(x: 15, y: 80, width: titleWidth, height: 25)
//        self.view.addSubview(hot)
        
        recentTitleView.frame = CGRect(x: 0, y: saperator.frame.origin.y + saperator.frame.height + 15, width: self.view.bounds.width, height: 30)
        self.view.addSubview(recentTitleView)
        
        textfield.beginFloatingCursor(at: CGPoint(x: 0, y: 0))
        
        loadRecentSearch()
    }
    
    func loadRecentSearch() {
        recentSearch = db.quaryData()
        let gap: CGFloat = self.view.bounds.width / 9
        if recentSearch.count > 0 {
            for i in 0...recentSearch.count - 1 {
                let label = UILabel()
                label.layer.borderColor = proceededColor.cgColor
                label.layer.borderWidth = 1
                label.layer.cornerRadius = 8
                label.textColor = proceededColor
                label.font = AppFont(size: 14)
                label.textAlignment = .center
                label.text = recentSearch[i].search
                label.frame = CGRect(x: gap + (gap * 4) * CGFloat(i % 2), y: recentTitleView.frame.origin.y + recentTitleView.frame.height + gap + (gap * 1.5) * CGFloat(Int(i / 2)), width: gap * 3, height: gap / 1.5)
                labels.append(label)
                self.view.addSubview(label)
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            for label in labels {
                if label.frame.contains(point) {
                    self.textfield.text = label.text
                    break
                }
            }
            if !textfield.frame.contains(point) {
                textfield.resignFirstResponder()
            }
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    func editing() {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.searchIcon.frame = CGRect(x: 60, y: 35, width: 15, height: 15)
            self.textfield.frame = CGRect(x: 80, y: 34, width: 160, height: 17)
        })
    }
    
    func finishEditing() {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.searchIcon.frame = CGRect(x: 90, y: 35, width: 15, height: 15)
            self.textfield.frame = CGRect(x: 110, y: 34, width: 160, height: 17)
        })
    }
}

extension SearchViewController: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.editing()
    }
    
    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
        self.finishEditing()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let completion = self.completion {
            completion(textfield.text!)
            if textField.text != "" {
                db.insertData(RecentSearch(search: textfield.text!))
            }
            self.navigationController?.popViewController(animated: true)
            return true
        }
        return false
    }
}
